package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.assist;


import com.longrise.common.utils.PrintLog;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by godliness on 2017/9/13.
 * 提交进的任务按照FIFO执行
 * 用于处理学习部分耗时任务
 */

public final class CacheTask {

    private static final String TAG = "CacheTask";

    private static volatile ExecutorService mExecutor;

    private static final ReentrantLock mLock = new ReentrantLock();

    private CacheTask() {
    }

    private static void create() {
        if (isClose()) {
            ReentrantLock lock = mLock;
            try {
                lock.lock();
                if (isClose()) {
                    mExecutor = Executors.newSingleThreadExecutor();
                    PrintLog.e(TAG, "create");
                }
            } finally {
                lock.unlock();
            }
        }
    }

    private static boolean isClose() {
        if (mExecutor == null || mExecutor.isShutdown()) {
            return true;
        }
        return false;
    }

    /**
     * 提交任务
     *
     * @param task
     */
    public static void submit(Runnable task) {
        create();
        if (mExecutor != null) {
            mExecutor.submit(task);
        }
    }

    /**
     * 不在接收任务
     */
    public static void shutdownTask() {
        if (mExecutor != null) {
            mExecutor.shutdown();
        }
        mExecutor = null;
    }
}
